package com.common.library.util;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import android.Manifest;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.AlertDialog.Builder;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.support.v4.content.ContextCompat;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.WindowManager.LayoutParams;
import android.view.inputmethod.InputMethodManager;
import android.widget.PopupWindow;
import android.widget.RemoteViews;
import android.widget.Toast;


import com.zs4sdk.Zs4GameBase;
import com.zs4sdk.Zs4GameMenu;
import com.zs4sdk.activity.Zs4GameDownloadApkActivity;
import com.zs4sdk.common.Extra;
import com.common.library.data.CommonEventHandler;
import com.common.library.data.EventHandler2Get;
import com.zs4sdk.entity.Zs4GameData;
import com.zs4sdk.entity.MessageResultEntity;
import com.zs4sdk.extra.Zs4GameCode;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import static com.zs4sdk.Zs4GameBase.getPackageName;

/**
 * Activity辅助类
 *
 * @author chengfu.bao
 */
public class ActivityHelper {

    private static final String TAG = ActivityHelper.class.getSimpleName();

    private static Context sApplicationContext;

    /**
     * 初始化(初次使用前必须调用,全局只需调用一次)
     *
     * @param applicationContext
     */
    public static void init(Context applicationContext) {
        sApplicationContext = applicationContext;
    }

    /**
     * 取得全局的ApplicationContext
     *
     * @return
     */
    public static Context getGlobalApplicationContext() {
        if (Helper.isNull(sApplicationContext)) {
            //Log.d(TAG, "MUST BE CALL 'ActivityHelper.init(Context)' IN YOUR ACTIVITY BEFORE USE 'ActivityHelper.getGlobalApplicationContext()'");
        }
        return sApplicationContext;
    }

    //#region Toast集
    private static Toast mToast;

    private static Toast getToast() {
        if (mToast == null) {
            mToast = Toast.makeText(getGlobalApplicationContext(), "", Toast.LENGTH_SHORT);//new Toast(context);
        }
        return mToast;
    }

    /**
     * 显示Toast信息(短)
     *
     * @param resId      显示文本的资源ID
     * @param formatArgs 字符串格式化参数
     */
    public static void showToast(int resId, Object... formatArgs) {
        showToast(Toast.LENGTH_SHORT, resId, formatArgs);
    }

    /**
     * 显示Toast信息(短)
     *
     * @param text 显示文本
     */
    public static void showToast(CharSequence text) {
        showToast(Toast.LENGTH_SHORT, text);
    }

    /**
     * 显示Toast信息(长)
     *
     * @param resId      显示文本的资源ID
     * @param formatArgs 字符串格式化参数
     */
    public static void showLongToast(int resId, Object... formatArgs) {
        showToast(Toast.LENGTH_LONG, resId, formatArgs);
    }

    /**
     * 显示Toast信息(长)
     *
     * @param text 显示文本
     */
    public static void showLongToast(CharSequence text) {
        showToast(Toast.LENGTH_LONG, text);
    }
    /**
     * 显示Toast信息(长)
     *
     * @param text 显示文本
     */
    public static void showLongToast(Context context,CharSequence text) {
       //showToast(Toast.LENGTH_LONG, text);
        Toast.makeText(context, text, Toast.LENGTH_SHORT).show();//new Toast(context);
    }
    /**
     * 显示Toast信息
     *
     * @param duration   时长
     * @param resId      显示文本的资源ID
     * @param formatArgs 字符串格式化参数
     */
    private static void showToast(int duration, int resId, Object... formatArgs) {
        try {
            showToast(duration, getString(resId, formatArgs));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 显示Toast信息
     *
     * @param duration 时长
     * @param text     显示文本
     */
    private static void showToast(int duration, CharSequence text) {
        try {
            Toast toast = getToast();
            if (Helper.isNotNull(toast)) {
                //4.0伤不起啊..
//				toast.cancel();
                toast.setText(text);
                toast.setDuration(duration);
                toast.show();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //#endregion Toast集

    //#region ProgressDialog 集
    private static ProgressDialog mProgressDialog;

    private static ProgressDialog getProgressDialog(Context ctx) {
        if (mProgressDialog == null) {
            mProgressDialog = ProgressDialog.show(ctx, "", "", false, true);
        }
        return mProgressDialog;
    }

    /**
     * 显示ProgressDialog，无标题
     *
     * @param messageId 消息
     */
    public static void showProgressDialog(Context ctx, int messageId) {
        showProgressDialog(ctx, "", ctx.getString(messageId), false, true);
    }

    /**
     * 显示ProgressDialog，无标题
     *
     * @param message
     */
    public static void showProgressDialog(Activity activity, String message) {
        showProgressDialog(activity, "", message, false, true);
    }

    /**
     * 显示ProgressDialog
     */
    public static void showProgressDialog(Activity activity, int titleId, int messageId) {
        showProgressDialog(activity, activity.getString(titleId), activity.getString(messageId), false, true);
    }

    /**
     * 显示ProgressDialog
     *
     * @param title   标题
     * @param message
     */
    public static void showProgressDialog(Activity activity, String title, String message) {
        showProgressDialog(activity, title, message, false, true);
    }

    /**
     * 显示ProgressDialog，自定义
     *
     * @param title
     * @param message
     * @param indeterminate
     * @param cancelable
     */
    public static void showProgressDialog(Context ctx, String title, String message, boolean indeterminate, boolean cancelable) {
        showProgressDialog(ctx, title, message, indeterminate, cancelable, true);
    }

    /**
     * 显示ProgressDialog，自定义
     *
     * @param title
     * @param message
     * @param indeterminate
     * @param cancelable
     * @param onceMore      出错时是否再执行一次
     */
    private static void showProgressDialog(Context ctx, String title, String message, boolean indeterminate, boolean cancelable, boolean onceMore) {
        if (Helper.isNotNull(ctx)) {
//		if (Helper.isNotNull(ctx) && !ctx.isFinishing()){
            try {
                getProgressDialog(ctx).dismiss();
                getProgressDialog(ctx).setTitle(title);
                getProgressDialog(ctx).setMessage(message);
                getProgressDialog(ctx).setIndeterminate(indeterminate);
                getProgressDialog(ctx).setCancelable(cancelable);
                getProgressDialog(ctx).show();
            } catch (Exception e) {
                e.printStackTrace();
                dismissProgressDialog();
                mProgressDialog = null;
                if (onceMore) {
                    showProgressDialog(ctx, title, message, indeterminate, cancelable, false);
                }
            }
        }
    }

    /**
     * 关闭进度框
     */
    public static void dismissProgressDialog() {
        try {
            if (Helper.isNotNull(mProgressDialog)) {
                mProgressDialog.dismiss();
                mProgressDialog = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //#endregion ProgressDialog 集

    //#region Properties存取操作
//	/**
//	 * 载入属性配置
//	 * @param context 上下文
//	 * @param file 文件名
//	 * @return 属性配置
//	 */
//	public static Properties loadProperties(Context context, String file){
//		Properties properties = new Properties();
//		try{
//			FileInputStream inputStream = context.openFileInput(file); //new FileInputStream(file);
//			properties.load(inputStream);
//		}catch(Exception e){
//			e.printStackTrace();
//		}
//		return properties;
//	}
//	/**
//	 * 保存属性配置
//	 * @param context 上下文
//	 * @param file 文件名
//	 * @param properties 属性配置
//	 * @return 是否成功者
//	 */
//	public static boolean saveProperties(Context context, String file, Properties properties){
//		try{
//			FileOutputStream outputStream = context.openFileOutput(file, Context.MODE_PRIVATE);
//			properties.store(outputStream, "");
//			return true;
//		}catch(Exception e){
//			e.printStackTrace();
//			return false;
//		}
//	}
//	/**
//	 * 载入XML属性配置
//	 * @param context 上下文
//	 * @param file 文件名
//	 * @return 属性配置
//	 */
//	public static Properties loadXMLProperties(Context context, String file){
//		Properties properties = new Properties();
//		try{
//			FileInputStream inputStream = context.openFileInput(file); //new FileInputStream(file);
//			properties.loadFromXML(inputStream);
//		}catch(Exception e){
//			e.printStackTrace();
//		}
//		return properties;
//	}
//	/**
//	 * 保存XML属性配置
//	 * @param context 上下文
//	 * @param file 文件名
//	 * @param properties 属性配置
//	 * @return 是否成功者
//	 */
//	public static boolean saveXMLProperties(Context context, String file, Properties properties){
//		try{
//			FileOutputStream outputStream = context.openFileOutput(file, Context.MODE_PRIVATE);
//			properties.storeToXML(outputStream, "");
//			return true;
//		}catch(Exception e){
//			e.printStackTrace();
//			return false;
//		}
//	}
    //#endregion Properties存取操作

    //#region 延迟任务执行
//	/**
//	 * 延迟重复执行任务
//	 * @param delayMS 延迟毫秒数
//	 * @param listener 监听
//	 */
//	public static DelayTask doDelayTask(int delayMS, OnDelayExecuteListener listener){
//		return doDelayTask(delayMS, 0, listener);
//	}
//	/**
//	 * 延迟重复执行任务
//	 * @param delayMS 延迟毫秒数
//	 * @param repeatCount 重复次数
//	 * @param listener 监听
//	 */
//	public static DelayTask doDelayTask(int delayMS, int repeatCount, OnDelayExecuteListener listener){
//		DelayTask result = new DelayTask(delayMS, repeatCount, listener);
//		result.start();
//		return result;
//	}
    //#endregion 延迟任务执行

    //#region 通过字符串名称取得res下的资源

    /**
     * 取得资源字符串
     *
     * @param resId
     * @return
     */
    public static String getString(int resId) {
        return getGlobalApplicationContext().getString(resId);
    }

    public static int getColor(int resId) {
        return getGlobalApplicationContext().getResources().getColor(resId);
    }

    /**
     * 取得资源字符串
     *
     * @param resId
     * @param formatArgs
     * @return
     */
    public static String getString(int resId, Object... formatArgs) {
        return getGlobalApplicationContext().getString(resId, formatArgs);
    }

    /**
     * 取得指定名称的bitmap
     *
     * @param imageName 图片名称
     * @return
     */
    public static Bitmap getBitmapByName(String imageName) {
        Bitmap result = null;
        try {
            int resId = getImageResId(imageName);
            if (resId > 0) {
                result = BitmapFactory.decodeResource(getGlobalApplicationContext().getResources(), resId);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return result;
    }

    /**
     * 取得指定名称的Drawable
     *
     * @param imageName 图片名称
     * @return
     */
    public static Drawable getDrawableByName(String imageName) {
        Drawable result = null;
        try {
            int resId = getImageResId(imageName);
            if (resId > 0) {
                result = getGlobalApplicationContext().getResources().getDrawable(resId);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 取得指定名称的图片资源ID
     *
     * @param imageName 图片名称
     * @return
     */
    public static int getImageResId(String imageName) {
        return Helper.getImageResId(getGlobalApplicationContext(), getGlobalApplicationContext().getPackageName(), imageName);
    }

    /**
     * 取得指定名称的图片资源ID
     *
     * @return
     */
    public static int getColorResId(String colorName) {
        return Helper.getColorResId(getGlobalApplicationContext(), getGlobalApplicationContext().getPackageName(), colorName);
    }

    /**
     * function: 取得指定名称的dimen资源ID
     *
     * @return
     * @ author: aXiBa 2013-3-15 上午10:56:42
     */
    public static int getDimenResId(String dimenName) {
        return Helper.getDimenResId(getGlobalApplicationContext(), getGlobalApplicationContext().getPackageName(), dimenName);
    }

    /**
     * 取得指定名称的字符串资源ID
     *
     * @param stringName 字符串名称
     * @return
     */
    public static int getStringResId(String stringName) {
        return Helper.getStringResId(getGlobalApplicationContext(), getGlobalApplicationContext().getPackageName(), stringName);
    }
    /**
     * 取得指定style资源ID
     *
     * @param stringName 字符串名称
     * @return
     */
    public static int getStyleResId(String stringName) {
        return Helper.getStyleResId(getGlobalApplicationContext(), getGlobalApplicationContext().getPackageName(), stringName);
    }

    /**
     * 取得指定名称的布局资源id
     *
     * @param layoutName
     * @return
     */
    public static int getLayoutResId(String layoutName) {
        return Helper.getLayoutResId(getGlobalApplicationContext(), getGlobalApplicationContext().getPackageName(), layoutName);
    }

    /**
     * 取得指定名称的动画资源id
     *
     * @param animName
     * @return
     */
    public static int getAnimResId(String animName) {
        return Helper.getAnimResId(getGlobalApplicationContext(), getGlobalApplicationContext().getPackageName(), animName);
    }

    /**
     * 取得指定名称的资源id
     *
     * @param idName
     * @return
     */
    public static int getIdResId(String idName) {
        return Helper.getIdResId(getGlobalApplicationContext(), getGlobalApplicationContext().getPackageName(), idName);
    }

    /**
     * 取得指定名称的资源raw
     *
     * @param idName
     * @return
     */
    public static int getRawResId(String idName) {
        return Helper.getRawResId(getGlobalApplicationContext(), getGlobalApplicationContext().getPackageName(), idName);
    }

    /**
     * 取得指定名称的样式id
     *
     * @param styleableString
     * @return
     */
    public static int getStyleableResId(String styleableString) {
        return Helper.getStyleableResId(getGlobalApplicationContext(), getGlobalApplicationContext().getPackageName(), styleableString);
    }

    /**
     * 取得指定名称的数组资源
     *
     * @param arrayName 数组名称
     * @return
     */
    public static String[] getStringArray(String arrayName) {
        Resources r = getGlobalApplicationContext().getResources();
        return r.getStringArray(r.getIdentifier(arrayName, "array", getGlobalApplicationContext().getPackageName()));
    }
    //#endregion 通过字符串名称取得res下的资源


    //#region Dialog集

    /**
     * 创建对话框Builder
     *
     * @param context
     * @param icon       图标，为null时不显示
     * @param title      标题
     * @param message    显示信息
     * @param cancelable 是否可取消
     * @return 对话框Builder
     */
    public static Builder createDialogBuilder(Context context, Drawable icon, String title, String message, boolean cancelable) {
        Builder builder = new Builder(context).setTitle(title).setCancelable(cancelable);
        if (Helper.isNotNull(icon)) {
            builder.setIcon(icon);
        }
        if (Helper.isNotEmpty(message)) {
            builder.setMessage(message);
        }
        return builder;
    }

    /**
     * 创建对话框Builder
     *
     * @param context
     * @param icon       图标，为0时不显示
     * @param title      标题
     * @param message    显示信息
     * @param cancelable 是否可取消
     * @return 对话框Builder
     */
    public static Builder createDialogBuilder(Context context, int icon, int title, int message, boolean cancelable) {
        Builder builder = new Builder(context).setTitle(title).setCancelable(cancelable);
        if (icon != 0) {
            builder.setIcon(icon);
        }
        if (message != 0) {
            builder.setMessage(message);
        }
        return builder;
    }

    /**
     * 创建对话框Builder
     *
     * @param context
     * @param icon       图标，为0时不显示
     * @param title      标题
     * @param message    显示信息
     * @param cancelable 是否可取消
     * @return 对话框Builder
     */
    public static Builder createDialogBuilder(Context context, int icon, String title, String message, boolean cancelable) {
        Builder builder = new Builder(context).setTitle(title).setCancelable(cancelable);
        if (icon != 0) {
            builder.setIcon(icon);
        }
        if (Helper.isNotEmpty(message)) {
            builder.setMessage(message);
        }
        return builder;
    }

    /**
     * 创建对话框Builder
     *
     * @param context
     * @param icon               对话框图标,为0则不显示
     * @param title              标题
     * @param message            显示信息
     * @param cancelable         是否可取消
     * @param positiveButtonText 确认按钮文字，空则使用默认
     * @param positiveListener   确认事件，null则只执行关闭对话框
     * @param negativeButtonText 否认按钮文字，空则使用默认
     * @param negativeListener   否认事件，null则只执行关闭对话框
     * @param neutralButtonText  中立按钮文字，空则不使用此按钮
     * @param neutralListener    中立事件，null则只执行关闭对话框
     */
    public static Builder createDialogBuilder(
            Context context, int icon, String title, String message, boolean cancelable
            , String positiveButtonText, OnClickListener positiveListener
            , String negativeButtonText, OnClickListener negativeListener
            , String neutralButtonText, OnClickListener neutralListener
    ) {
        Builder builder = createDialogBuilder(context, icon, title, message, cancelable);
        //确认按钮
        String text = positiveButtonText;
        OnClickListener listener = positiveListener;
        if (Helper.isEmpty(text)) {
            text = context.getString(android.R.string.ok);
        }
        if (Helper.isNull(listener)) {
            listener = new OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            };
        }
        builder.setPositiveButton(text, listener);
        //否定按钮
        text = negativeButtonText;
        listener = negativeListener;
        if (Helper.isEmpty(text)) {
            text = context.getString(android.R.string.cancel);
        }
        if (Helper.isNull(listener)) {
            listener = new OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            };
        }
        builder.setNegativeButton(text, listener);
        //中立按钮
        if (Helper.isNotEmpty(neutralButtonText)) {
            text = neutralButtonText;
            listener = neutralListener;
            if (Helper.isNull(listener)) {
                listener = new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                };
            }
            builder.setNeutralButton(text, listener);
        }

        return builder;
    }

    /**
     * 显示提示对话框（无图标，点击后关闭）
     *
     * @param context
     * @param title      标题
     * @param message    显示信息
     * @param cancelable 是否可取消
     */
    public static void showAlertDialog(Context context, String title, String message, boolean cancelable) {
        showAlertDialog(context, 0, title, message, cancelable, null);
    }

    /**
     * 显示提示对话框
     *
     * @param context
     * @param icon       对话框图标,为0则不显示
     * @param title      标题
     * @param message    显示信息
     * @param cancelable 是否可取消
     * @param listener   点击事件
     */
    public static void showAlertDialog(Context context, int icon, String title, String message, boolean cancelable, OnClickListener listener) {
		try{
        Builder builder = createDialogBuilder(context, icon, title, message, cancelable);
        if (Helper.isNull(listener)) {
            builder.setPositiveButton(android.R.string.ok, new OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
        } else {
            builder.setPositiveButton(android.R.string.ok, listener);
        }
        builder.create().show();
		}catch (Exception e) {
			e.printStackTrace();
		}
    }

    /**
     * 显示提示对话框
     *
     * @param context
     * @param icon               对话框图标,为0则不显示
     * @param title              标题
     * @param message            显示信息
     * @param cancelable         是否可取消
     * @param positiveButtonText 点击文本
     * @param listener           点击事件
     */
    public static void showAlertDialog(Context context, int icon, String title, String message, boolean cancelable, int positiveButtonText, OnClickListener listener) {
		try{
        Builder builder = createDialogBuilder(context, icon, title, message, cancelable);
        if (Helper.isNull(listener)) {
            builder.setPositiveButton(positiveButtonText, new OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
        } else {
            builder.setPositiveButton(positiveButtonText, listener);
        }
        builder.create().show();
		}catch (Exception e) {
			e.printStackTrace();
		}
    }

    /**
     * function: 两个按钮dialog
     *
     * @param context
     * @param icon
     * @param title
     * @param message
     * @param cancelable
     * @param positiveButtonText
     * @param positiveListener
     * @param negativeButtonText
     * @param negativeListener
     * @ author: aXiBa 2013-3-27 下午7:09:14
     */
    public static void showAlertDialog(Context context, int icon, String title, String message, boolean cancelable,
                                       int positiveButtonText, OnClickListener positiveListener,
                                       int negativeButtonText, OnClickListener negativeListener) {
//		try{
        Builder builder = createDialogBuilder(context, icon, title, message, cancelable);
        builder.setPositiveButton(positiveButtonText, positiveListener);
        builder.setNegativeButton(negativeButtonText, negativeListener);
        builder.create().show();
//		}catch (Exception e) {
//			e.printStackTrace();
//		}
    }

    /**
     * 显示确认对话框(两键,默认取消的行为只有关闭)
     *
     * @param context
     * @param icon               为0则无icon
     * @param title              标题
     * @param message            显示信息
     * @param cancelable         是否可取消
     * @param positiveButtonText 确认按钮文字，空则使用默认
     * @param positiveListener   确认事件，null则只执行关闭对话框
     */
    public static void showConfirmDialog(
            Context context, int icon, String title, String message, boolean cancelable
            , int positiveButtonText, OnClickListener positiveListener) {
        showConfirmDialog(context, icon, title, message, cancelable
                , positiveButtonText, positiveListener
                , 0, null
                , 0, null
        );
    }

    /**
     * 显示确认对话框(两键，无icon)
     *
     * @param context
     * @param title              标题
     * @param message            显示信息
     * @param cancelable         是否可取消
     * @param positiveButtonText 确认按钮文字，空则使用默认
     * @param positiveListener   确认事件，null则只执行关闭对话框
     * @param negativeButtonText 否认按钮文字，空则使用默认
     * @param negativeListener   否认事件，null则只执行关闭对话框
     */
    public static void showConfirmDialog(
            Context context, String title, String message, boolean cancelable
            , int positiveButtonText, OnClickListener positiveListener
            , int negativeButtonText, OnClickListener negativeListener
    ) {
        showConfirmDialog(context, 0, title, message, cancelable
                , positiveButtonText, positiveListener
                , negativeButtonText, negativeListener
                , 0, null
        );
    }

    /**
     * 显示确认对话框
     *
     * @param context
     * @param icon               对话框图标,为0则不显示
     * @param title              标题
     * @param message            显示信息
     * @param cancelable         是否可取消
     * @param positiveButtonText 确认按钮文字，空则使用默认
     * @param positiveListener   确认事件，null则只执行关闭对话框
     * @param negativeButtonText 否认按钮文字，空则使用默认
     * @param negativeListener   否认事件，null则只执行关闭对话框
     * @param neutralButtonText  中立按钮文字，空则不使用此按钮
     * @param neutralListener    中立事件，null则只执行关闭对话框
     */
    public static void showConfirmDialog(
            Context context, int icon, String title, String message, boolean cancelable
            , int positiveButtonText, OnClickListener positiveListener
            , int negativeButtonText, OnClickListener negativeListener
            , int neutralButtonText, OnClickListener neutralListener
    ) {
        showConfirmDialog(context, icon, title, message, cancelable
                , positiveButtonText == 0 ? null : context.getString(positiveButtonText), positiveListener
                , negativeButtonText == 0 ? null : context.getString(negativeButtonText), negativeListener
                , neutralButtonText == 0 ? null : context.getString(neutralButtonText), neutralListener
        );
    }

    /**
     * 显示确认对话框
     *
     * @param context
     * @param icon               对话框图标,为0则不显示
     * @param title              标题
     * @param message            显示信息
     * @param cancelable         是否可取消
     * @param positiveButtonText 确认按钮文字，空则使用默认
     * @param positiveListener   确认事件，null则只执行关闭对话框
     * @param negativeButtonText 否认按钮文字，空则使用默认
     * @param negativeListener   否认事件，null则只执行关闭对话框
     * @param neutralButtonText  中立按钮文字，空则不使用此按钮
     * @param neutralListener    中立事件，null则只执行关闭对话框
     */
    public static void showConfirmDialog(
            Context context, int icon, String title, String message, boolean cancelable
            , String positiveButtonText, OnClickListener positiveListener
            , String negativeButtonText, OnClickListener negativeListener
            , String neutralButtonText, OnClickListener neutralListener
    ) {
        try {
            Builder builder = createDialogBuilder(
                    context, icon, title, message, cancelable
                    , positiveButtonText, positiveListener
                    , negativeButtonText, negativeListener
                    , neutralButtonText, neutralListener
            );

            builder.create().show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //#endregion Dialog集

    //#region Notification集
    /**
     * 状态栏提示的默认ID
     */
    private static int NOTIFICATION_DEFAULT_ID = Helper.createIntTag();

    /**
     * 显示默认状态栏提示
     *
     * @param pIcon
     * @param pTickerText    提示时显示的滚动信息,null时则不滚动显示
     * @param pContentTitle  内容标题
     * @param pContentText   内容
     * @param pContentView   点击显示的内容View,无则null
     * @param pContentIntent 点击跳转用PendingIntent
     */
    public static void showDefaultNotification(
            final Context pContext
            , final int pIcon
            , final int pTickerText
            , final int pContentTitle
            , final int pContentText
            , final RemoteViews pContentView
            , final PendingIntent pContentIntent
    ) {
        showNotification(pContext, 0, pIcon, pTickerText, pContentTitle, pContentText, pContentView, pContentIntent);
    }

    /**
     * 显示默认状态栏提示
     *
     * @param pContext
     * @param pIcon
     * @param pTickerText    提示时显示的滚动信息,null时则不滚动显示
     * @param pContentTitle  内容标题
     * @param pContentText   内容
     * @param pContentView   点击显示的内容View,无则null
     * @param pContentIntent 点击跳转用PendingIntent
     */
    public static void showDefaultNotification(
            final Context pContext
            , final int pIcon
            , final CharSequence pTickerText
            , final CharSequence pContentTitle
            , final CharSequence pContentText
            , final RemoteViews pContentView
            , final PendingIntent pContentIntent
    ) {
        showNotification(pContext, 0, pIcon, pTickerText, pContentTitle, pContentText, pContentView, pContentIntent);
    }

    /**
     * 显示状态栏提示
     *
     * @param pId            ID,0则采用默认值
     * @param pIcon
     * @param pTickerText    提示时显示的滚动信息,null时则不滚动显示
     * @param pContentTitle  内容标题
     * @param pContentText   内容
     * @param pContentView   点击显示的内容View,无则null
     * @param pContentIntent 点击跳转用PendingIntent
     */
    public static void showNotification(
            final Context pContext
            , final int pId
            , final int pIcon
            , final int pTickerText
            , final int pContentTitle
            , final int pContentText
            , final RemoteViews pContentView
            , final PendingIntent pContentIntent
    ) {
        showNotification(pContext, pId, pIcon
                , pContext.getText(pTickerText), pContext.getText(pContentTitle), pContext.getText(pContentText), pContentView, pContentIntent);
    }

    /**
     * 显示状态栏提示
     *
     * @param pContext
     * @param pId            ID,0则采用默认值
     * @param pIcon
     * @param pTickerText    提示时显示的滚动信息,null时则不滚动显示
     * @param pContentTitle  内容标题
     * @param pContentText   内容
     * @param pContentView   点击显示的内容View,无则null
     * @param pContentIntent 点击跳转用PendingIntent
     */
    public static void showNotification(
            final Context pContext
            , final int pId
            , final int pIcon
            , final CharSequence pTickerText
            , final CharSequence pContentTitle
            , final CharSequence pContentText
            , final RemoteViews pContentView
            , final PendingIntent pContentIntent
    ) {
        showNotification(pContext, pId, pIcon, pTickerText, pContentTitle, pContentText, pContentView, pContentIntent, true);
    }

    /**
     * 显示状态栏提示
     *
     * @param pContext
     * @param pId            ID,0则采用默认值
     * @param pIcon
     * @param pTickerText    提示时显示的滚动信息,null时则不滚动显示
     * @param pContentTitle  内容标题
     * @param pContentText   内容
     * @param pContentView   点击显示的内容View,无则null
     * @param pContentIntent 点击跳转用PendingIntent
     * @param pCancelLast    是否立即取消上一个提示
     */
    public static void showNotification(
            final Context pContext
            , final int pId
            , final int pIcon
            , final CharSequence pTickerText
            , final CharSequence pContentTitle
            , final CharSequence pContentText
            , final RemoteViews pContentView
            , final PendingIntent pContentIntent
            , final boolean pCancelLast
    ) {
        int id = pId == 0 ? NOTIFICATION_DEFAULT_ID : pId;
        NotificationManager notificationManager = (NotificationManager) pContext.getSystemService(Context.NOTIFICATION_SERVICE);
        if (pCancelLast) {
            notificationManager.cancel(id);
        }
        Notification notification = new Notification(pIcon, pTickerText, System.currentTimeMillis());
        if (Helper.isNotNull(pContentView)) {
            notification.contentView = pContentView;
        }
//		notification.setLatestEventInfo(pContext, pContentTitle, pContentText, pContentIntent);
        notificationManager.notify(id, notification);
    }

    /**
     * 取消默认状态栏通知
     *
     * @param pContext
     */
    public static void cancelDefaultNotification(final Context pContext) {
        cancelNotification(pContext, 0);
    }

    /**
     * 取消状态栏通知
     *
     * @param pContext
     * @param pId      通知ID,0则为默认值
     */
    public static void cancelNotification(final Context pContext, final int pId) {
        NotificationManager notificationManager = (NotificationManager) pContext.getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.cancel(pId == 0 ? NOTIFICATION_DEFAULT_ID : pId);
    }
    //#endregion Notification集


    //#region PopupWindow

    /**
     * 创建PopupWindow(可touch,区域外touch,可聚焦)
     *
     * @param pActivity     创建的Activity,非context
     * @param pViewLayoutId 内部View布局id
     * @return
     */
    public static PopupWindow createPopupWindow(
            Activity pActivity
            , int pViewLayoutId
    ) {
        return createPopupWindow(
                pActivity, pViewLayoutId
                , LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT
                , true, true, true);
    }

    /**
     * 创建PopupWindow(可touch,区域外touch,可聚焦)
     *
     * @param pActivity     创建的Activity,非context
     * @param pViewLayoutId 内部View布局id
     * @param pWidth        创建的宽度(可采用LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT之类)
     * @param pHeight       创建的高度(可采用LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT之类)
     * @return
     */
    public static PopupWindow createPopupWindow(
            Activity pActivity
            , int pViewLayoutId
            , int pWidth
            , int pHeight
    ) {
        return createPopupWindow(
                pActivity, pViewLayoutId, pWidth, pHeight, true, true, true);
    }

    /**
     * 创建PopupWindow
     *
     * @param pActivity         创建的Activity,非context
     * @param pViewLayoutId     内部View布局id
     * @param pWidth            创建的宽度(可采用LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT之类)
     * @param pHeight           创建的高度(可采用LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT之类)
     * @param pTouchable        是否可touch
     * @param pOutsideTouchable 是否可在区域外touch
     * @param pFocusable        是否可聚焦
     * @return
     */
    public static PopupWindow createPopupWindow(
            Activity pActivity
            , int pViewLayoutId
            , int pWidth
            , int pHeight
            , boolean pTouchable
            , boolean pOutsideTouchable
            , boolean pFocusable
    ) {
        PopupWindow result = null;
        View contentView = pActivity.getLayoutInflater().inflate(pViewLayoutId, null);
        result = new PopupWindow(contentView, pWidth, pHeight, pFocusable);
        result.setTouchable(pTouchable);
        result.setOutsideTouchable(pOutsideTouchable);
        return result;
    }
    //#endregion PopupWindow


    //#region 便捷方法
    private static float sDisplayMetricsDensity = -1;

    /**
     * 计算DPI值对应的PX
     *
     * @param dpi
     * @return
     */
    public static int calDpi2px(int dpi) {
        if (dpi == 0) {
            return dpi;
        }
        if (sDisplayMetricsDensity < 0) {
            sDisplayMetricsDensity = getGlobalApplicationContext().getResources().getDisplayMetrics().density;
        }
        return Helper.float2Int(dpi * sDisplayMetricsDensity);
    }

    private static int[] sScreenSize = null;

    /**
     * 取得屏幕尺寸(0:宽度; 1:高度)
     *
     * @return
     */
    public static int[] getScreenSize() {
        if (sScreenSize == null) {
            sScreenSize = new int[2];
            DisplayMetrics dm = getGlobalApplicationContext().getResources().getDisplayMetrics();
            sScreenSize[0] = dm.widthPixels;
            sScreenSize[1] = dm.heightPixels;
        }
        return sScreenSize;
    }

    /**
     * 取得屏幕宽度
     *
     * @return
     */
    public static int getScreenWidth() {
        return getScreenSize()[0];
    }

    /**
     * 取得屏幕高度
     *
     * @return
     */
    public static int getScreenHeight() {
        return getScreenSize()[1];
    }

    /**
     * 从URI取得bitmap
     *
     * @param context
     * @param uri
     * @return
     */
    public static Bitmap getBitmapFromUri(Context context, Uri uri) {
        Bitmap result = null;
        InputStream is = null;
        try {
            is = context.getContentResolver().openInputStream(uri);
            if (Helper.isNotNull(is)) {
                result = BitmapFactory.decodeStream(is, null, null);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (Helper.isNotNull(is)) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return result;
    }

    /**
     * Bitmap反失真用Paint
     */
    private static Paint mBitmapPaint = null;

    /**
     * 取得Bitmap用反失真Paint
     */
    public static Paint getDrawBitmapPaint() {
        if (Helper.isNull(mBitmapPaint)) {
            mBitmapPaint = new Paint();
            mBitmapPaint.setAntiAlias(true);
            mBitmapPaint.setFilterBitmap(true);
            mBitmapPaint.setDither(true);
        }
        return mBitmapPaint;
    }

    /**
     * 取得当前软件版本
     *
     * @return
     */
    public static int getCurrentVersion() {
        int versionCode = 0;
        try {
            PackageInfo info = getGlobalApplicationContext().getPackageManager()
                    .getPackageInfo(getGlobalApplicationContext().getPackageName(), 0);
            versionCode = info.versionCode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return versionCode;
    }

    /**
     * 取得当前软件版本名称
     *
     * @return
     */
    public static String getCurrentVersionName() {
        String versionName = "";
        try {
            PackageInfo info = getGlobalApplicationContext().getPackageManager()
                    .getPackageInfo(getGlobalApplicationContext().getPackageName(), 0);
            versionName = info.versionName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return versionName;
    }


    /**
     * function: 得到Application的icon
     *
     * @return
     * @ author: aXiBa 2013-3-27 下午2:42:59
     */
    public static Drawable getApplicationIcon() {

        try {
            return getGlobalApplicationContext().getPackageManager().getApplicationIcon(getGlobalApplicationContext().getPackageName());
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return null;
    }


    /**
     * function: 得到Application的label
     *
     * @return
     * @ author: aXiBa 2013-3-27 下午2:44:15
     */
    public static String getApplicationLabel() {

        ApplicationInfo mApplicationInfo;
        try {
            mApplicationInfo = getGlobalApplicationContext().getPackageManager().getApplicationInfo(getGlobalApplicationContext().getPackageName(), 0);
            return getGlobalApplicationContext().getPackageManager().getApplicationLabel(mApplicationInfo).toString();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 是否ROOT
     *
     * @return
     */
    public static boolean isRoot() {
        try {
            new File("/root").list();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 取得mac地址
     *
     * @return
     */
    public static String getMacAddress() {
//		String mac = "11:11:11:11:11:16";
        String mac = "";
        try {
            WifiManager wifi = (WifiManager) getGlobalApplicationContext().getSystemService(Context.WIFI_SERVICE);
            mac = wifi.getConnectionInfo().getMacAddress();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (Helper.isNull(mac)) {
            return "";
        }
        LogUtil.w(TAG, "wifi mac: " + mac);
        return mac;
    }


    /**
     * 取得基本的保存路径(无SD卡则使用RAM)
     *
     * @return
     */
    public static String getBaseCachePath() {
        String result = null;
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
                && Environment.getExternalStorageDirectory().canWrite()) {
            result = getGlobalApplicationContext().getExternalCacheDir().getAbsolutePath().concat(File.separator);
        }
        if (Helper.isEmpty(result)) {
            result = getGlobalApplicationContext().getCacheDir().getPath().concat(File.separator);
        }
        return result;
    }

    /**
     * 隐藏软键盘
     *
     * @param view
     */
    public static void hideSoftInputFromWindow(View view) {
        if (Helper.isNotNull(view)) {
            InputMethodManager imm = (InputMethodManager) getGlobalApplicationContext()
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }
    //#endregion 便捷方法

    //#region Activity基类使用方法

    /**
     * 控制指定view的显示状态
     *
     * @param activity
     * @param visiblity 是否显示(可取值有View.VISIBLE, View.GONE, View.INVISIBLE)
     * @param viewIds
     */
    public static final void visibleViews(Activity activity, int visiblity, int... viewIds) {
        for (int viewId : viewIds) {
            View view = (View) activity.findViewById(viewId);
            if (Helper.isNotNull(view)) {
                view.setVisibility(visiblity);
            }
        }
    }

    /**
     * 控制指定view的显示状态
     *
     * @param activity
     * @param visiblity 是否显示(可取值有View.VISIBLE, View.GONE, View.INVISIBLE)
     * @param viewIds
     */
    public static final void visibleViews(Activity activity, int visiblity, String... viewIds) {
        for (String viewId : viewIds) {
            View view = (View) activity.findViewById(ActivityHelper.getIdResId(viewId));
            if (Helper.isNotNull(view)) {
                view.setVisibility(visiblity);
            }
        }
    }

    /**
     * 控制指定view的显示状态
     *
     * @param visiblity 是否显示(可取值有View.VISIBLE, View.GONE, View.INVISIBLE)
     */
    public static final void visibleViews(int visiblity, View... views) {
        for (View view : views) {
            if (Helper.isNotNull(view)) {
                view.setVisibility(visiblity);
            }
        }
    }
    /**
     * 跳转到指定Activity(不结束当前的)
     * @param activity
     * @param toActivity
     */
//	public static final void switchTo(Activity activity, Class<?> toActivity){
//		switchTo(activity, toActivity, false);
//	}
//	public static final void switchTo(Activity activity, Class<?> toActivity, Bundle bundle){
//		switchTo(activity, toActivity, false, bundle);
//	}
//	/**
//	 * 跳转到指定Activity(不结束当前的)
//	 * @param activity 
//	 * @param toActivity
//	 * @param enterAnim 进入动画
//	 * @param exitAnim 退出动画
//	 */
//	public static final void switchTo(Activity activity, Class<?> toActivity, int enterAnim, int exitAnim) {
//		switchTo(activity, toActivity, false, 0, 0);
//	}
//	/**
//	 * 跳转到指定Activity
//	 * @param activity 
//	 * @param toActivity
//	 * @param finish 是否结束当前Activity
//	 */
//	public static final void switchTo(Activity activity, Class<?> toActivity, boolean finish){
//		switchTo(activity, toActivity, finish, 0, 0);
//	}
//	public static final void switchTo(Activity activity, Class<?> toActivity, boolean finish, Bundle bundle){
//		switchTo(activity, toActivity, finish, 0, 0, bundle);
//	}
//	/**
//	 * 跳转到指定Activity
//	 * @param activity 
//	 * @param toActivity
//	 * @param finish 是否结束当前Activity
//	 * @param enterAnim 进入动画
//	 * @param exitAnim 退出动画
//	 */
//	public static final void switchTo(Activity activity, Class<?> toActivity, boolean finish, int enterAnim, int exitAnim){
//		Intent intent = new Intent(activity, toActivity);
//		activity.startActivity(intent);
//		if (finish){
//			activity.finish();
//		}
//		if (enterAnim != 0 && exitAnim != 0){
//			try{
//				activity.overridePendingTransition(enterAnim, exitAnim);
//			}catch (Exception e) {
//				e.printStackTrace();
//			}
//		}
//	}
//	public static final void switchTo(Activity activity, Class<?> toActivity, boolean finish, int enterAnim, int exitAnim, Bundle bundle){
//		Intent intent = new Intent(activity, toActivity);
//		intent.putExtras(bundle);
//		activity.startActivity(intent);
//		if (finish){
//			activity.finish();
//		}
//		if (enterAnim != 0 && exitAnim != 0){
//			try{
//				activity.overridePendingTransition(enterAnim, exitAnim);
//			}catch (Exception e) {
//				e.printStackTrace();
//			}
//		}
//	}

    /**
     * 设置指定View的监听
     *
     * @param activity
     * @param listener
     * @param viewIds
     */
    public static final void setViewClickEvent(Activity activity, View.OnClickListener listener, int... viewIds) {
        if (Helper.isNotNull(listener) && Helper.isNotEmpty(viewIds)) {
            for (int viewId : viewIds) {
                View view = activity.findViewById(viewId);
                if (Helper.isNotNull(view)) {
                    view.setOnClickListener(listener);
                }
            }
        }
    }

    /**
     * 设置指定View的监听
     *
     * @param activity
     * @param listener
     * @param viewIds
     */
    public static final void setViewClickEvent(Activity activity, View.OnClickListener listener, String... viewIds) {
        if (Helper.isNotNull(listener) && Helper.isNotEmpty(viewIds)) {
            for (String viewId : viewIds) {
                View view = activity.findViewById(ActivityHelper.getIdResId(viewId));
                if (Helper.isNotNull(view)) {
                    view.setOnClickListener(listener);
                }
            }
        }
    }

    /**
     * 设置指定View的监听
     *
     * @param parentView
     * @param listener
     * @param viewIds
     */
    public static final void setViewClickEvent(View parentView, View.OnClickListener listener, int... viewIds) {
        if (Helper.isNotNull(listener) && Helper.isNotEmpty(viewIds)) {
            for (int viewId : viewIds) {
                View view = parentView.findViewById(viewId);
                if (Helper.isNotNull(view)) {
                    view.setOnClickListener(listener);
                }
            }
        }
    }

    /**
     * 设置指定View的监听
     *
     * @param listener
     * @param views
     */
    public static final void setViewClickEvent(View.OnClickListener listener, View... views) {
        if (Helper.isNotNull(listener) && Helper.isNotEmpty(views)) {
            for (View view : views) {
                if (Helper.isNotNull(view)) {
                    view.setOnClickListener(listener);
                }
            }
        }
    }

    /**
     * 判断指定的服务是否已启动
     *
     * @param serviceFullName 服务全名(包括包名)
     * @return
     */
    public static final boolean isServiceRunning(String serviceFullName) {
        return isServiceRunning(getGlobalApplicationContext(), serviceFullName);
    }

    /**
     * 判断指定的服务是否已启动
     *
     * @param context
     * @param serviceFullName 服务全名(包括包名)
     * @return
     */
    public static final boolean isServiceRunning(Context context, String serviceFullName) {
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningServiceInfo> runningServices = manager.getRunningServices(40);
        if (Helper.isNotEmpty(runningServices)) {
            for (RunningServiceInfo runningService : runningServices) {
                if (runningService.service.getClassName().toString().equals(serviceFullName)) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 判断某个intent是否可用
     * <p> e.g. 判断系统是否可以处理mailto数据：
     * <p>intent = new Intent(Intent.ACTION_VIEW, Uri.parse());
     *
     * @param context 上下文
     * @param intent  intent
     * @return 是否可用
     */
    public static final boolean isIntentAvailable(Context context, Intent intent) {
        final PackageManager packageManager = context.getPackageManager();
        List<ResolveInfo> list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
        return list.size() > 0;
    }


    /**
     * function: 发广播
     *
     * @param action
     * @param code
     * @param context
     * @ author: aXiBa 2013-3-18 下午3:45:18
     */
    public static void sendBroadcast(String action, int code, Context context) {

        Intent intent = new Intent();
        intent.setAction(action);
        intent.putExtra(Extra.INTENTKEY.CODE, code);
        context.sendBroadcast(intent);
    }


    public static void sendBroadcast(String action, int code, int type, Context context) {

        if (Zs4GameCode.LOGINSUCCESS == code) {
//            requestMsg(context);
        }

        Intent intent = new Intent();
        intent.setAction(action);
        intent.putExtra(Extra.INTENTKEY.CODE, code);

        Bundle bundle = new Bundle();
        bundle.putInt(Zs4GameBase.TPYE, type);
        intent.putExtras(bundle);

        context.sendBroadcast(intent);
    }

    private static void requestMsg(Context context) {

        SharedPreferences sharedPreferences = context.getSharedPreferences(Extra.LAST_TIMESTAMP, Context.MODE_PRIVATE);
        final SharedPreferences.Editor editor = sharedPreferences.edit();//获取编辑器

        String timestamp = sharedPreferences.getString(Zs4GameData.getInstance().getUserId()+Extra.LAST_TIMESTAMP, "");

        ArrayList<NameValuePair> paramList = new ArrayList<NameValuePair>();
        paramList.add(new BasicNameValuePair("timestamp", timestamp));

        new EventHandler2Get(
                Extra.URL.GET_COUNT_KEFU,
                paramList,
                ParamsHelper.getUserAgent1(),
                new CommonEventHandler.ResultHandlerInEvent() {

                    @Override
                    public void doResultHanler(JSONObject result) throws JSONException {
//                        LogUtil.i(TAG, "请求消息： " + result);
                        MessageResultEntity messageResultEntity = new MessageResultEntity(result);
                        if(messageResultEntity.isSuccess()){
                            Zs4GameData.getInstance().setCountKefuMessage(messageResultEntity.getNum());
//                        Zs4GameData.getInstance().setCountKefuMessage(1);
                            editor.putString(Zs4GameData.getInstance().getUserId()+Extra.LAST_REQUEST_TIME,messageResultEntity.getTimestamp());
                            editor.commit();
                        }
                    }

                    @Override
                    public void doExceptionHandler() {

                    }
                });

    }


    /**
     * function: sendLoginSuccessBroadcast
     *
     * @param isSwitchAccount
     * @param type
     * @param ctx
     * @param flag
     * @ author: aXiBa 2013-12-15 下午10:15:33
     */
    public static void sendLoginSuccessBroadcast(boolean isSwitchAccount, int type, Context ctx, String flag) {

        // 从菜单
        if (Extra.FLAG_MENU.equals(flag) || Extra.FLAG_MANUAL_MENU.equals(flag)) {
            if (isSwitchAccount) {
                sendBroadcast(getPackageName().concat(Extra.ACTIONKEY.MESSAGE_POSTFIX), Zs4GameCode.SWITCHACCOUNT, type, ctx);
            } else {
                sendBroadcast(getPackageName().concat(Extra.ACTIONKEY.MESSAGE_POSTFIX), Zs4GameCode.LOGINSUCCESS, type, ctx);
            }
        }
        // 独立模块调用
        else {
            sendBroadcast(flag, Zs4GameCode.LOGINSUCCESS, type, ctx);
        }
        Zs4GameMenu.closeActivitysAndShowStartMenu(ctx, flag);
    }

    /**
     * function: 发广播(带参数)
     *
     * @param action
     * @param code
     * @param context
     * @param bundle
     * @ author: aXiBa 2013-5-11 下午1:02:56
     */
    public static final void sendBroadcast(String action, int code, Context context, Bundle bundle) {

        Intent intent = new Intent();
        intent.setAction(action);
        intent.putExtra(Extra.INTENTKEY.CODE, code);
        intent.putExtras(bundle);
        context.sendBroadcast(intent);
    }


    public static final void sendBroadcast(String action, int code, int type, Context context, Bundle bundle) {

        Intent intent = new Intent();
        intent.setAction(action);
        intent.putExtra(Extra.INTENTKEY.CODE, code);
        bundle.putInt(Zs4GameBase.TPYE, type);
        intent.putExtras(bundle);
        context.sendBroadcast(intent);
    }


    /**
     * 检查是否有读写权限
     *
     * @return
     */
    public static boolean checkPermission_WRITE_EXTERNAL_STORAGE() {

        if (Build.VERSION.SDK_INT < 23 || (Build.VERSION.SDK_INT >= 23 &&
                (ContextCompat.checkSelfPermission(ActivityHelper.getGlobalApplicationContext(),
                        Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED))) {
            return true;
        } else {

            return false;
        }
    }


    //#endregion Activity基类使用方法

    /**
     * 替换手机号码中间4位为****
     *
     * @param phoneNumber
     * @return
     */
    public static String setPhone(String phoneNumber) {
        if(Helper.checkMobile(phoneNumber)){
            StringBuffer buffer = new StringBuffer(phoneNumber);
            return buffer.replace(3, 7, "****").toString();
        }else return "";
    }

    /**
     * 打开设置页面授权
     */
    public static void openSetting(Context context){
        final int apiLevel = Build.VERSION.SDK_INT;
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        if (apiLevel >= 9) { // 2.3（ApiLevel 9）以上，使用SDK提供的接口
            intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            Uri uri = Uri.fromParts("package", getPackageName(), null);
            intent.setData(uri);
        } else { // 2.3以下，使用非公开的接口（查看InstalledAppDetails源码）
            // 2.2和2.1中，InstalledAppDetails使用的APP_PKG_NAME不同。
            final String appPkgName = (apiLevel == 8 ?  "pkg":
                    "com.android.settings.ApplicationPkgName");
            intent.setAction(Intent.ACTION_VIEW);
            intent.setClassName("com.android.settings",
                    "com.android.settings.InstalledAppDetails");
            intent.putExtra(appPkgName,  getPackageName());
        }
        context.startActivity(intent);
    }
//#endregion Activity基类使用方法

    public static boolean checkChannel(String channel){
        return true;
    }


    /**
     * 获取应用名称
     * @return
     */
    public static String getApplicationName() {
        PackageManager packageManager = null;
        ApplicationInfo applicationInfo = null;
        try {
            packageManager = getGlobalApplicationContext().getPackageManager();
            applicationInfo = packageManager.getApplicationInfo(getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            applicationInfo = null;
        }
        String applicationName =
                (String) packageManager.getApplicationLabel(applicationInfo);
        return applicationName;
    }

    /**
     * 调起下载
     * @param context
     * @param title
     * @param url
     * @param isClose 是否下载页面可以关闭
     */
    public static  void gotoDownload(Context context, String title,String url,String flag,boolean isClose) {
        Intent intent = new Intent(context, Zs4GameDownloadApkActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString(Extra.INTENTKEY.TITLE, title);
        bundle.putString(Extra.INTENTKEY.URL, url);
        bundle.putBoolean(Extra.INTENTKEY.INTENT_TYPE, isClose);
        bundle.putString(Extra.INTENTKEY.FLAG, flag);
        intent.putExtras(bundle);
        context.startActivity(intent);
    }


    /**
     * 创建指定数量的随机字符串
     * @param numberFlag 是否是数字
     * @param length
     * @return
     */
    public static String createRandom(boolean numberFlag, int length){
        String retStr = "";
        String strTable = numberFlag ? "1234567890" : "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        int len = strTable.length();
        boolean bDone = true;
        do {
            retStr = "";
            int count = 0;
            for (int i = 0; i < length; i++) {
                double dblR = Math.random() * len;
                int intR = (int) Math.floor(dblR);
                char c = strTable.charAt(intR);
                if (('0' <= c) && (c <= '9')) {
                    count++;
                }
                retStr += strTable.charAt(intR);
            }
            if (count >= 2) {
                bDone = false;
            }
        } while (bDone);

        return retStr;
    }
}
